#include "PacketFormat.h"
#include <string.h>
#include <stdio.h>
#include <sstream>

using namespace std;

PacketFormat::PacketFormat() {

}

PacketFormat::PacketFormat(char c, char i, int l, string d) {
	code = c;
	identifier = i;
	length = l;
	data = d;
}

PacketFormat::PacketFormat(const PacketFormat& orig) {
	this->code = orig.code;
	this->identifier = orig.identifier;
	this->length = orig.length;
	this->data = orig.data;
}

//Construct a packet from input as a string (form of abc00001blah blah blah)
PacketFormat::PacketFormat (string strPack){

	this->code = strPack[0];
	this->identifier = strPack[1];

	string slen = strPack.substr(2, 2) + "\0";

	int first = (int)slen[0];
	int second = (int)slen[1];

	this->length = 256 * first + second;
	data = strPack.substr(4, strPack.size()-4);
}

PacketFormat::~PacketFormat() {
	//we do not use dynamic memory allocation in this class, so this function is empty
}

string PacketFormat::compilePacket() {
	string res = "";
	char c1 = length >> 8;
	char c2 = length & 0xFF;

	string slen = string(1,c1) + string(1,c2);
	res += string(1, code) + identifier + slen + data;
	//cout << res << "\n";
	return res;
}

void PacketFormat::print(){
	cout << "code = " << this->code << "\n";
	cout << "id = " << this->identifier << "\n";
	cout << "length = " << this->length << "\n";
	cout << "data = " << this->data << "\n";
}

//get and set function
void PacketFormat::setCode(int c){
	code = c;
}
void PacketFormat::setId (int i){
	identifier = i;
}
void PacketFormat::setLength(int l){
	length = l;
}
void PacketFormat::setData(string d){
	data = d;
}
char PacketFormat::getCode(){
	return code;
}
char PacketFormat::getId(){
	return identifier;
}
int PacketFormat::getLength(){
	return length;
}
string PacketFormat::getData(){
	return data;
}


